package com.cqhz.quwan.ui.main.fragment

import android.content.Intent
import android.graphics.Color
import android.os.CountDownTimer
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.loadmore.LoadMoreView
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.MatchBean
import com.cqhz.quwan.model.MatchItemBean
import com.cqhz.quwan.model.PageResultBean
import com.cqhz.quwan.mvp.home.LiveContract
import com.cqhz.quwan.mvp.home.LivePresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.base.AbsFragment
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.main.match.MatchAnalysisActivity
import com.cqhz.quwan.ui.widget.LoadMoreGoneView
import com.cqhz.quwan.util.CLogger
import com.cqhz.quwan.util.CommonAdapterHelper
import com.cqhz.quwan.util.UmengAnalyticsHelper
import com.gavin.com.library.PowerfulStickyDecoration
import com.gavin.com.library.listener.PowerGroupListener
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.fragment_guess.*
import kotlinx.android.synthetic.main.fragment_live.*
import me.militch.quickcore.core.HasDaggerInject
import javax.inject.Inject

/**
 * 首页-直播页面
 * Created by Guojing on 2018/9/13.
 */
class LiveFragment : AbsFragment(), LiveContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var livePresenter: LivePresenter
    private var status: Int = 1// status 赛事状态 1：即时（当日比赛）2：完场 3：赛程（次日及之后赛事）
    private var titles = arrayOf("全部", "竞彩", "中超", "欧冠", "英超", "德甲", "西甲", "意甲", "法甲")
    private var pages = ArrayList<View>()
    private var pagesIndex = ArrayList<Int>()
    private var holders = ArrayList<PageViewHolder>()
    private var adapters = ArrayList<BaseQuickAdapter<*, *>>()
    private var groups = ArrayList<ArrayList<MatchBean>>()
    private var childrens = ArrayList<ArrayList<MatchItemBean>>()
    private var countDownTimer: CountDownTimer? = null

    override fun inject(t: ActivityInject?) {
        t!!.inject(this)
    }

    companion object {
        fun newInstance() = LiveFragment()
    }

    override fun layout(): Int {
        return R.layout.fragment_live
    }

    override fun initView() {
        livePresenter.attachView(this)

        // 初始化页面元素和相应数据以及适配器
        for (i in 1..titles.size) {
            initAdapter()
        }
        initPager()

        rg_select_status.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.action_select_upcoming -> status = 1
                R.id.action_select_finished -> status = 2
                R.id.action_select_underway -> status = 3
            }

            vp_content.currentItem = 0
            refreshCurrentPage(0, pagesIndex[0])
        }
        action_goto_award.setOnClickListener {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title, "")
            intent.putExtra(KeyContract.EnableRefresh, false)
            val url = API.FOOTBALL_INFORMATION
            val l = CLogger(this::class.java)
            l.d("url", url)
            intent.putExtra(KeyContract.Url, url)
            startActivity(intent)
        }
        refreshPage()
    }

    /**
     * 初始化列表适配器
     */
    private fun initAdapter() {
        // 当前页面的布局
        var pageView = LayoutInflater.from(context()).inflate(R.layout.layout_page, vp_content, false) as View
        var holder = PageViewHolder(pageView)
        var pageIndex = 1

        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(context()).inflate(R.layout.layout_none, holder.rvContent.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据和适配器
        var matchList = ArrayList<MatchBean>()
        var matchItemList = ArrayList<MatchItemBean>()
        var countDownMap = SparseArray<CountDownTimer>()
        var matchListAdapter = CommonAdapterHelper.getLiveListAdapter(context(), matchItemList, countDownMap)
        matchListAdapter.emptyView = emptyView
        matchListAdapter.setLoadMoreView(LoadMoreGoneView())

        // 当前页面列表适配器的事件
        holder.rvContent.layoutManager = LinearLayoutManager(context())
        holder.rvContent.adapter = matchListAdapter
        matchListAdapter.setOnLoadMoreListener({
            var currentPage = vp_content.currentItem
            if (groups[currentPage].size > 0) {
                if (groups[currentPage].size % KeyContract.pageSize == 0) {
                    var pageNo = groups[currentPage].size / KeyContract.pageSize + 1
                    holders[currentPage].refreshLayout.isEnableRefresh = false
                    refreshCurrentPage(currentPage, pageNo)
                } else {
                    adapters[currentPage].loadMoreEnd()
                }
            } else {
                holders[currentPage].refreshLayout.isEnableRefresh = false
                refreshCurrentPage(currentPage, 1)
            }
        }, holder.rvContent)
        holder.rvContent.addOnItemTouchListener(object : OnItemClickListener() {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                var currentPage = vp_content.currentItem
                val item = adapters[currentPage].getItem(position) as MatchItemBean
                MatchAnalysisActivity.start(context, item.matchId, item.lid)
            }
        })
        // 刷新
        holder.refreshLayout.setOnRefreshListener {
            var currentPage = vp_content.currentItem
            refreshCurrentPage(currentPage, 1)
        }

        // 将当前的页面、列表控件、数据列表、适配器加入相应的列表
        pages.add(pageView)
        pagesIndex.add(pageIndex)
        holders.add(holder)
        groups.add(matchList)
        childrens.add(matchItemList)
        adapters.add(matchListAdapter)
    }

    private fun getItemDecoration(): RecyclerView.ItemDecoration {
        var currentPage = vp_content.currentItem
        val groupListener = object : PowerGroupListener {
            override fun getGroupView(position: Int): View {
                val view = layoutInflater.inflate(R.layout.item_live_head, null, false)
                var tvMatchTime = view.findViewById(R.id.tv_match_time) as TextView
                if (childrens[currentPage].size > 0 && position <= childrens[currentPage].size - 1) {
                    val child = childrens[currentPage][position]
                    tvMatchTime.text = child.groupName
                } else {
                    tvMatchTime.text = "数据加载完毕"
                    tvMatchTime.setBackgroundColor(Color.parseColor("#ffffff"))
                }
                return view
            }

            override fun getGroupName(position: Int): String {
                if (childrens[currentPage].size > 0 && position <= childrens[currentPage].size - 1) {
                    val child = childrens[currentPage][position]
                    return child.groupName
                }
                return ""
            }
        }

        return PowerfulStickyDecoration.Builder
                .init(groupListener)
                .build()
    }


    /**
     * 初始化页面
     */
    private fun initPager() {
        vp_content.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return pages.size
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(pages[position])
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                var view = pages[position]
                var parent = view.parent as? ViewGroup
                parent?.removeAllViews()
                container.addView(view)
                return view
            }
        }
        st_tab.setViewPager(vp_content, titles)
        vp_content.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                if (groups[position].size <= 0) {
                    refreshCurrentPage(position, pagesIndex[position])
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    /**
     * 实时刷新当前页面
     */
    private fun refreshPage() {
        // 倒计时刷新
        val time = "3600".toLong() * 60 * 1000
        // 将前一个缓存清除
        if (countDownTimer != null) {
            countDownTimer!!.cancel()
        }
        countDownTimer = object : CountDownTimer(time, 15000) {
            override fun onTick(millisUntilFinished: Long) {
                var currentPage = vp_content.currentItem
                refreshCurrentPage(currentPage, pagesIndex[currentPage])
            }

            override fun onFinish() {
                showToast("请放下手机，休息一下吧")
            }
        }.start()
    }

    override fun loadMatchLiveList(currentPage: Int, pageNo: Int, pageResultBean: PageResultBean<MatchBean>) {
        if (pageNo == 1) {
            groups[currentPage].clear()
            childrens[currentPage].clear()
            adapters[currentPage].setEnableLoadMore(true)
            if (holders[currentPage].refreshLayout.state.isHeader!!) {
                holders[currentPage].refreshLayout.finishRefresh()
            }
        }

        if (pageResultBean.records.isNotEmpty()) {
            for (i in 0 until pageResultBean.records.size) {
                groups[currentPage].add(pageResultBean.records[i])
                for (j in 0 until pageResultBean.records[i].matchResultList.size) {
                    var child = pageResultBean.records[i].matchResultList[j]
                    child.groupPosition = i
                    child.childPosition = j
                    child.groupSize = pageResultBean.records.size
                    child.childSize = pageResultBean.records[i].matchResultList.size
                    child.groupName = pageResultBean.records[i].matchTime + " " + pageResultBean.records[i].matchField
                    childrens[currentPage].add(child)
                }
            }

            // 需要在setLayoutManager()之后调用addItemDecoration()
            if (holders[currentPage].rvContent.itemDecorationCount > 0) {
                holders[currentPage].rvContent.removeItemDecorationAt(0)
            }
            holders[currentPage].rvContent.addItemDecoration(getItemDecoration())
        }

        if (pageResultBean.total > groups[currentPage].size) {
            adapters[currentPage].loadMoreComplete()
        } else {
            adapters[currentPage].loadMoreEnd()
        }

        adapters[currentPage].notifyDataSetChanged()
        holders[currentPage].refreshLayout.isEnableRefresh = true
    }

    internal class PageViewHolder(view: View) {
        var rvContent = view.findViewById(R.id.rv_content) as RecyclerView
        var refreshLayout = view.findViewById(R.id.refreshLayout) as SmartRefreshLayout
    }

    /**
     * 刷新当前页面
     */
    private fun refreshCurrentPage(currentPage: Int, pageNo: Int) {
        livePresenter.getMatchLiveList(pageNo.toString(), KeyContract.pageSize.toString(), status, currentPage)
    }

    override fun onResume() {
        super.onResume()
        UmengAnalyticsHelper.onPageStart("直播")// 统计页面
        UmengAnalyticsHelper.onResume(context())

        var currentPage = vp_content.currentItem
        refreshCurrentPage(currentPage, pagesIndex[currentPage])
        refreshPage()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!isHidden) {
            this.onResume()
        } else {
            this.onPause()
            if (refreshLayout.state.isFinishing) {
                refreshLayout.finishRefresh()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        livePresenter.detachView()
        if (countDownTimer != null) {
            countDownTimer!!.cancel()
        }
    }

    override fun onPause() {
        super.onPause()
        if (countDownTimer != null) {
            countDownTimer!!.cancel()
        }
        UmengAnalyticsHelper.onPageEnd("直播")// 统计页面
        UmengAnalyticsHelper.onPause(context())
    }
}